import { defineStore } from 'pinia';
import { http } from '@/utils/request';
import type { CheckoutInfo, SubmitOrder } from '@/types';
import { message } from '@/components/XtxUI';
import useStore from '..';
import router from '@/router';
// 订单仓库
export const useOrderStore = defineStore('order', {
  persist: true,
  state() {
    return {
      checkInfo: {} as CheckoutInfo,
      orderDetail: {},
    };
  },
  getters: {
    // defaultAddress(state) {
    //   return state.checkInfo.userAddresses[0];
    // },
  },
  actions: {
    async getCheckInfo() {
      const res = await http<CheckoutInfo>('get', '/member/order/pre');
      console.log('订单', res);
      this.checkInfo = res.data.result;
    },

    // 添加地址。
    async addAdress(address) {
      try {
        const res = await http('post', '/member/address', address);
        console.log(res, '新增地址');
        this.getCheckInfo();
        message({
          type: 'success',
          text: '添加地址成功！',
        });
      } catch (e) {
        message({
          type: 'error',
          text: '添加地址出错了！',
        });
      }
    },

    // 提交订单
    async createOrder(data: object) {
      const res = await http<SubmitOrder>('post', '/member/order', data);
      console.log('订单提交', res);
      // 成功提醒用户
      message({ type: 'success', text: '下单成功~' });
      // 🔔刷新购物车列表
      const { cart } = useStore();
      cart.getCartInfo();
      // 跳转到支付页并传递订单 id
      router.replace('/member/pay?orderId=' + res.data.result.id);
    },

    // 获取订单详情
    async getOrderDetail(orderId: string) {
      const res = await http('get', `/member/order/${orderId}`);
      this.orderDetail = res.data.result as object;
      console.log('订单详情', this.orderDetail);
    },
  },
});
